package com.sakura.takeaway.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sakura.takeaway.common.BaseContext;
import com.sakura.takeaway.common.CustomException;
import com.sakura.takeaway.common.R;
import com.sakura.takeaway.entity.ShoppingCart;
import com.sakura.takeaway.service.ShopingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Sakura
 * @Date 2022-07-15 13:59
 */
@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class ShoppingCartController {

    @Autowired
    private ShopingCartService shopingCartService;

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        log.info("购物车数据：{}",shoppingCart);

        //设置用户id,指定当前是哪个用户的购物车数据
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);

        //判断添加到购物车的是套餐还是菜品
        Long dishId = shoppingCart.getDishId();
        //添加构造器
        LambdaQueryWrapper<ShoppingCart> queryWrapper =new LambdaQueryWrapper<>();
        //判断是哪个用户
        queryWrapper.eq(ShoppingCart::getUserId,currentId);

        if(dishId!=null){
            //添加到购物车的是菜品
            queryWrapper.eq(ShoppingCart::getDishId,dishId);
        }else {
            //添加到购物车的是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }

        //查询当前菜品是否在购物车中
        //SQL:select * from shopping_cart where user_id = ? and dish_id/setmeal_id =?
        ShoppingCart cartServiceOne = shopingCartService.getOne(queryWrapper);

        if(cartServiceOne!=null){
            //存在，在原来的数量上+1
            Integer number = cartServiceOne.getNumber();
            cartServiceOne.setNumber(number+1);
            shopingCartService.updateById(cartServiceOne);
        }else {
            //不存在，在原来的数量上-1
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shopingCartService.save(shoppingCart);
            cartServiceOne = shoppingCart;
        }

        return R.success(cartServiceOne);
    }

    /**
     * 查看购物车
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        log.info("查看购物车...");

        LambdaQueryWrapper<ShoppingCart> queryWrapper =new LambdaQueryWrapper();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        queryWrapper.orderByAsc(ShoppingCart::getCreateTime);

        List<ShoppingCart> list = shopingCartService.list(queryWrapper);

        return R.success(list);
    }

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean(){

        //SQL:delete from shopping_cart where user_id =?

        LambdaQueryWrapper<ShoppingCart> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());

        shopingCartService.remove(queryWrapper);

        return R.success("清空购物车成功");
    }

    /**
     * 修改购物车  减少菜品
     * @param shoppingCart
     * @return
     */
    @Transactional
   @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart){

        //SQL:update shopping_cart set number=number-1 where user_id =? and dish_id/setmeal_id = ?

        //判断需要修改的是套餐还是菜品
        //获取菜品id
        Long dishId = shoppingCart.getDishId();

        LambdaQueryWrapper<ShoppingCart> queryWrapper =new LambdaQueryWrapper<>();

        if(dishId!=null){
            queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
            queryWrapper.eq(ShoppingCart::getDishId,dishId);
            ShoppingCart cartDishOne = shopingCartService.getOne(queryWrapper);
            //菜品进行减1
            cartDishOne.setNumber(cartDishOne.getNumber()-1);
            //减到0就不能继续减
            Integer LatestNumber = cartDishOne.getNumber();
            if(LatestNumber>0){
                //可以进行更新操作
                shopingCartService.updateById(cartDishOne);
            }else if(LatestNumber == 0){
                //如果购物车的菜品数量减为0，那么就把菜品从购物车删除
                shopingCartService.removeById(cartDishOne);
            }else if(LatestNumber < 0){
                throw new CustomException("操作异常");
            }
            return R.success(cartDishOne);
        }

        //获取套餐id
        Long setmealId = shoppingCart.getSetmealId();
        if(setmealId != null){
            queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
            queryWrapper.eq(ShoppingCart::getSetmealId,setmealId);
            ShoppingCart cartSetmealOne = shopingCartService.getOne(queryWrapper);
            //套餐数量-1
            cartSetmealOne.setNumber(cartSetmealOne.getNumber()-1);
            //减到0就不能继续减
            Integer LatestNumber = cartSetmealOne.getNumber();
            if(LatestNumber>0){
                shopingCartService.updateById(cartSetmealOne);
            }else if(LatestNumber == 0){
                shopingCartService.removeById(cartSetmealOne);
            }else if(LatestNumber < 0){
                throw new CustomException("操作异常");
            }
            return R.success(cartSetmealOne);

        }

        //如果都没有查询到
        return R.error("操作异常");
    }

}
